import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class SendingThread extends Thread {
	private String ip;
	private int port;
	private Socket socket;
	private File file;

	public SendingThread(String ip, int port, File file) {
		this.ip = ip;
		this.port = port;
		this.
		file = file;
	}

	public void run() {
		try {
			socket = new Socket(InetAddress.getByName(ip), port);

			byte[] mybytearray = new byte[(int) file.length()];
            FileInputStream fis = new FileInputStream(file);

            fis.read(mybytearray);
            P2PPackage myPackage = new P2PPackage(mybytearray, file.getName());
            // Package is ready to send
            
            BufferedReader in = new BufferedReader(new InputStreamReader(
    				socket.getInputStream()));
			ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            
			Module.writeToScreen(file.getName() + " is sending to" + InetAddress.getByName(ip));
			oos.writeObject(myPackage);
			// Package is sent
			synchronized (Module.getScreen()) {
				Module.writeToScreen(in.readLine() + " by " + InetAddress.getByName(ip));
				Module.writeToScreen("\n");
			}
            oos.close();
            fis.close();
            in.close();
            socket.close();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
